var hsjzh1 = 0;
var bhsjzh1 = 0;
var sezh1 = 0;
//var ddyfzh1=0;

String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}

$(function () {

    $("#cgjsd_gs").czgsjgqczcombobox({
        onSuccess: function () {
            $("#cgjsd_gs").zcombobox("setMap", { id: $("#cgjsd_content_gs_id").val(), qc: $("#cgjsd_content_gs_jc").val()});
        },
        onSelect: function () {
            var id_val = $('#cgjsd_gs').val();
        }
    });


//    $("#cgjsd_cggs").gsjgtree(1, {
//        onLoadSuccess:function () {
//            $("#cgjsd_cggs").combotree('readonly', true);
//        }
//    })

    $("#cgjsd_glqy").gsjgqczcombobox({
        onSuccess: function () {
            $("#cgjsd_glqy").zcombobox("setMap", { id: $("#cgjsd_content_gys_id").val(), qc: $("#cgjsd_content_gys_jc").val()});
        },
        onSelect: function () {
            var id_val = $('#cgjsd_glqy').val();
            $.post($.webPath() + '/xsgl/xsdgl/xsdKhById', {'xsgsId': id_val}, function (data) {
                $('#cgjsd_glqy_qyfr_nsh').val($.trim(data[0].nsh));
            })
        }
    });

//    $("#cgjsd_zbjs").unbind('click').bind('click', function () {
//        if ($(this).attr("checked") != undefined && $(this).attr("checked") == "checked") {
//            //TO-DO 赋值公司本部
//            $("#cgjsd_cggs").combotree('setValue', 1);
//        } else {
//            $("#cgjsd_cggs").combotree('setValue', $("#cgjsd_gs").val());
//        }
//    });

    if ($("#cgjsd_id").val()) {
        $("#cgjsd_zbjs").unbind('click').bind('click', function () {
            return false;
        });
    }

    var cgjsdId = $("#cgjsd_id").val() ? $("#cgjsd_id").val() : 0;
    $("#grid_cgjsdmx").edatagrid({
        url: $.webPath() + "/cggl/cgdgl/cgddmxSearchList?cgjsdId=" + cgjsdId || 0,
        fitColumns: false,
        singleSelect: true,
        width: 1000,
        height: 250,
        checkbox: true,
        fit: false,
        checkOnSelect: false,
        selectOnCheck: false,
        rownumbers: true,
        showFooter: true,
        frozenColumns: [
            [
                {field: 'checked', checkbox: true},
                {field: 'cgdh', title: '送货单号', width: 120},
                {field: 'wzgg.code', title: '物资编码', width: 100},
                {field: 'wzgg.name', title: '物资名称', width: 50},
                {field: 'wzgg.ggxh', title: '规格型号', width: 50},
                {field: 'ck', title: '长宽', width: 30},
                {field: 'wzgg.dw', title: '单位', width: 30}
            ]
        ],
        columns: [
            [
                {field: 'hsj', title: '含税价(元)', width: 100,
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }},
                {field: 'sjdj', title: '实际单价(元)', width: 100,
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }},
                {field: 'bhsj', title: '不含税价(元)', width: 100,
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }},
                {field: 'hse', title: '含税额(元)', width: 100,
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }},
                {field: 'bhse', title: '不含税额(元)', width: 100,
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }},
                {field: 'rksl', title: '数量', width: 70,
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }},
                {field: 'je', editor: {type: 'numberbox', options: {precision: 2, min: 0, groupSeparator: ','}}, title: '净额(元)', width: 100,
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }},
                {field: 'se', title: '税额(元)', width: 100, editor: {type: 'numberbox', options: {precision: 2, min: 0, groupSeparator: ','}},
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }},
                {field: 'ce', title: '差额(元)', width: 100,
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }}
            ]
        ],
//        loadFilter: function (data) {
//            $(data.rows).each(function () {
//                if (this.sjdj && this.sjdj != 0) {
//                    this.bhsj = (this.sjdj / 1.17).toFixed(6);
//                    this.hse = (this.sjdj * this.rksl).toFixed(6);
//                    this.bhse = ((this.sjdj * this.rksl) / 1.17).toFixed(6);
//                    this.je = ((this.sjdj * this.rksl) / 1.17).toFixed(6);
//                    this.se = ((this.sjdj * this.rksl) - ((this.sjdj * this.rksl) / 1.17)).toFixed(6);
//                }
//            })
//            return data;
//        },
        onClickRow: function (rowIndex, rowData) {
            //获取每个单元格
            $("#grid_cgjsdmx").edatagrid('editRow', rowIndex);
            var editors = $("#grid_cgjsdmx").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;
            var jeEditor = editors[0];//净额编辑框
            var seEditor = editors[1];//税额编辑框
            jeEditor.target.unbind("change").bind('change', function () {
                $(jeEditor.target).numberbox('setValue', $(jeEditor.target).val());

                rowData.ce = formatMoney(rowData.hse - (parseFloat($(jeEditor.target).numberbox('getValue')) + parseFloat(rowData.se)));
                var data = $("#grid_cgjsdmx").edatagrid('getData');
                var ce = 0.0, je = 0.0;
                for (var i = 0; i < data.rows.length; i++) {
                    if (i == rowIndex) {
                        ce += parseFloat(rowData.ce);
                        je += parseFloat($(jeEditor.target).numberbox('getValue'));
                    } else {
                        ce += parseFloat(data.rows[i].ce);
                        je += parseFloat(data.rows[i].je);
                    }
                }

                $("#cgjsd_ce").val(formatJeForHtml2(ce));
                $("#cgjsd_je").val(formatJeForHtml2(je));
                $("#cgjsd_me").val(formatJeForHtml2(countMe()));
                fpzeSum(countMe());

                /*   var zjbcdRows = $("#grid_zjbcd").datagrid('getRows');
                 var flag = false;
                 $.each(zjbcdRows, function (i, obj) {
                 if (obj['cgdmx.id'] == rowData['id']) {
                 if (rowData.ce != 0.0) {
                 $('#grid_zjbcd').datagrid('updateRow', {
                 index:i,
                 row:{
                 'lb.id':50,
                 'lb.z':'价格差',
                 'je':formatMoney(parseFloat(rowData.ce)),
                 'cgd.cgdh':rowData.cgdh,
                 'wzgg.code':rowData['wzgg.code'],
                 'wzgg.name':rowData['wzgg.name'],
                 'wzgg.ggxh':rowData['wzgg.ggxh'],
                 'wzgg.dw':rowData['wzgg.dw'],
                 'cgdmx.id':rowData['id'],
                 'cgd.id':rowData['cgd.id']
                 }
                 });
                 } else {
                 $('#grid_zjbcd').datagrid('deleteRow', i);
                 }

                 flag = true;
                 return false;
                 }
                 });
                 if (!flag && rowData.ce != 0) {
                 $("#grid_zjbcd").edatagrid('appendRow', {
                 'lb.z':'价格差',
                 'je':formatMoney(rowData.ce),
                 'cgd.cgdh':rowData.cgdh,
                 'cgd.id':rowData['cgd.id'],
                 'wzgg.code':rowData['wzgg.code'],
                 'wzgg.name':rowData['wzgg.name'],
                 'wzgg.ggxh':rowData['wzgg.ggxh'],
                 'wzgg.dw':rowData['wzgg.dw'],
                 'cgdmx.id':rowData['id'],
                 'lb.id':50
                 });
                 }*/
                countSumCg();
                $("#grid_cgjsdmx").edatagrid('saveRow');
//                    $("#grid_cgjsdmx").edatagrid('editRow', rowIndex);

            });
            seEditor.target.unbind("change").bind('change', function () {
                $(seEditor.target).numberbox('setValue', $(seEditor.target).val());
                //rowData.ce = formatMoney(rowData.hse - (parseFloat($(seEditor.target).numberbox('getValue')) + parseFloat(rowData.je)));
                var data = $("#grid_cgjsdmx").edatagrid('getData');
                var ce = 0.0, se = 0.0;
                for (var i = 0; i < data.rows.length; i++) {
                    if (i == rowIndex) {
                        // ce += parseFloat(rowData.ce);
                        se += parseFloat($(seEditor.target).numberbox('getValue'));
                    } else {
                        //ce += parseFloat(data.rows[i].ce);
                        se += parseFloat(data.rows[i].se);
                    }
                }

                //$("#cgjsd_ce").val(formatJeForHtml2(ce));
                $("#cgjsd_se").val(formatJeForHtml2(se));
                $("#cgjsd_me").val(formatJeForHtml2(countMe()));
                fpzeSum(countMe());

//                var zjbcdRows = $("#grid_zjbcd").datagrid('getRows');
//                var flag = false;
//                $.each(zjbcdRows, function (i, obj) {
//                    if (obj['cgdmx.id'] == rowData['id']) {
//                        if (rowData.ce != 0.0) {
//                            $('#grid_zjbcd').datagrid('updateRow', {
//                                index: i,
//                                row: {
//                                    'lb.id': 50,
//                                    'lb.z': '价格差',
//                                    'je': formatMoney(parseFloat(rowData.ce)),
//                                    'cgd.cgdh': rowData.cgdh,
//                                    'wzgg.code': rowData['wzgg.code'],
//                                    'wzgg.name': rowData['wzgg.name'],
//                                    'wzgg.ggxh': rowData['wzgg.ggxh'],
//                                    'wzgg.dw': rowData['wzgg.dw'],
//                                    'cgdmx.id': rowData['id'],
//                                    'cgd.id': rowData['cgd.id']
//                                }
//                            });
//                        } else {
//                            $('#grid_zjbcd').datagrid('deleteRow', i);
//                        }
//
//                        flag = true;
//                        return false;
//                    }
//                });
//                if (!flag && rowData.ce != 0) {
//                    $("#grid_zjbcd").edatagrid('appendRow', {
//                        'lb.z': '价格差',
//                        'je': formatMoney(rowData.ce),
//                        'cgd.cgdh': rowData.cgdh,
//                        'cgd.id': rowData['cgd.id'],
//                        'wzgg.code': rowData['wzgg.code'],
//                        'wzgg.name': rowData['wzgg.name'],
//                        'wzgg.ggxh': rowData['wzgg.ggxh'],
//                        'wzgg.dw': rowData['wzgg.dw'],
//                        'cgdmx.id': rowData['id'],
//                        'lb.id': 50
//                    });
//                }
                countSumCg();
                $("#grid_cgjsdmx").edatagrid('saveRow', rowIndex);
            });
        }
    })

    //发票总额的变换填充
//    $('#cgjsd_ddfy').focusout(function () {
//        fpzeSum();
//    });
    /*

     $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm':'zjbclb'}, function (data) {
     $("#grid_zjbcd").edatagrid({
     url:$.webPath() + "/jsgl/zjbcd/zjbcdSearchList?cgjsdId=" + cgjsdId || 0,
     fitColumns:true,
     singleSelect:true,
     fit:true,
     checkOnSelect:false,
     selectOnCheck:false,
     pagination:true,
     rownumbers:true,
     showFooter:true,
     columns:[
     [
     {field:'lb.id', editor:{type:'combobox', options:{
     data:data,
     valueField:'id',
     textField:'z',
     multiple:false,
     panelHeight:'78'
     }
     }, formatter:function (value) {
     for (var i = 0; i < data.length; i++) {
     if (data[i].id == value) return data[i].z;
     }
     return value;
     }, title:'类别', width:50},
     {field:'wzgg.code', title:'物资编码', width:50},
     {field:'wzgg.name', title:'物资名称', width:40},
     {field:'wzgg.ggxh', title:'规格型号', width:40},
     {field:'wzgg.dw', title:'单位', width:20},
     {field:'je', title:'金额(元)', width:50, options:{precision:2, min:0, groupSeparator:','},
     formatter:function (value) {
     var sl = formatJe2(value, ",");
     return sl;
     }},
     {field:'cgd.cgdh', title:'采购单', width:72}
     ]
     ],
     onSelect:function (rowIndex, rowData) {
     //获取每个单元格
     $("#grid_zjbcd").edatagrid('editRow', rowIndex);
     var editors = $("#grid_zjbcd").datagrid('getEditors', rowIndex);
     if (editors.length == 0)
     return;
     },
     onLoadSuccess:function () {
     countSumCg();
     }
     });
     });
     */

    //删除采购单的按钮触发
    $("#btn_cgjsd_cgd_del").click(function () {
        var cgdRow = $('#grid_cgjsdmx').datagrid('getChecked');
        $.each(cgdRow, function (i, val) {
            var cgdIndex = $('#grid_cgjsdmx').datagrid('getRowIndex', val);
            $('#grid_cgjsdmx').edatagrid('deleteRow', cgdIndex);
            /*var zjbcdRows = $("#grid_zjbcd").edatagrid('getRows');
             if (zjbcdRows && zjbcdRows.length > 0) {
             $.each(zjbcdRows, function (i, obj) {
             if (obj['cgdmx.id'] == val['id']) {
             var zjbcdIndex = $("#grid_zjbcd").datagrid('getRowIndex', obj);
             $('#grid_zjbcd').edatagrid('deleteRow', zjbcdIndex);
             }
             return false;
             });
             }*/
        })
        //统计净额、税额、面额、差额
        fillIntoFooter();
    });


    //搜索采购单
    $("#btn_cgjsd_cgd_search").click(function () {
//        var cgjsd_cggs = $("#cgjsd_cggs").combobox('getValue');
        var cgjsd_gs = $("#cgjsd_sbgs_id").val();
        var cgjsd_glqy = $("#cgjsd_glqy").val();
        if (cgjsd_glqy) {
            searccgdhwindow(grid_cgd_searchWindowOKbtnHandler, cgjsd_gs, cgjsd_gs, cgjsd_glqy);
        } else {
            $('#cgjsd_tabs').tabs('select', "结算单信息");
            $.messager.alert("提示", "请选择供应商!", "info");
        }
    });

    //供应商带出纳税号
//    $('#cgjsd_glqy').combobox({
//        onSelect: function () {
//            var obj = $('#cgjsd_glqy').combobox('getData');
//            var id_val = $('#cgjsd_glqy').combobox('getValue');
//            $.each(obj, function (i, val) {
//                if (obj[i].id == id_val) {
//                    $('#cgjsd_glqy_qyfr_nsh').val(obj[i].qyfr_nsh);
//                }
//            })
//        }
//    });
});


//查询采购单确定按钮回调函数
function grid_cgd_searchWindowOKbtnHandler(data) {
    var cgjsdData = $("#grid_cgjsdmx").datagrid("getRows");
    $.each(data, function () {
        var cgdid = this.id;
        var cgdh = this.cgdh;
        var cgjsdDsyfje = 0;
        var map = new Map();
        $.post($.webPath() + '/cggl/cgdgl/cgjsdSearch_cgdmx', {'cgd.id': cgdid}, function (mxData) {
            //cgjsdDsyfje += mxData.rows[0]['cgd.dsyfje'] == null ? 0 : mxData.rows[0]['cgd.dsyfje'];
            cgjsdDsyfje = !$("#cgjsd_ddfy").val() ? 0 : $("#cgjsd_ddfy").val();
            $.each(mxData.rows, function (i, j) {
                var flag = false;
                $.each(cgjsdData, function (r, obj) {
                    if (cgjsdData.length != 0 && obj['id'] == j['id']) {
                        flag = true;
                        return false;
                    }
                })
                if (!flag) {
                    if (!map.get(this['cgd.id']) && this['cgd.dsyfje'])
                        map.put(this['cgd.id'], this['cgd.dsyfje']);
                    var bhsj = !this['bhsj'] ? 0 : Math.round(this['bhsj'] * 10000) / 10000;
                    var sjdj = !this['sjdj'] ? 0 : Math.round(this['sjdj'] * 10000) / 10000;
                    var hsj = !this['hsj'] ? 0 : Math.round(this['hsj'] * 10000) / 10000;
                    var sl = !this['rksl'] ? 0 : Math.round(this['rksl'] * 10000) / 10000;
                    $("#grid_cgjsdmx").edatagrid('appendRow', {
                        'id': this.id,
                        'cgd.id': cgdid,
                        'cgdh': cgdh,
                        'wzgg.code': this['wzgg.code'],
                        'wzgg.name': this['wzgg.name'],
                        'wzgg.ggxh': this['wzgg.ggxh'],
                        'wzgg.dw': this['wzgg.dw'],
                        'ck': this['ck'],
                        'rksl': sl,
                        'bhsj': sjdj/1.17,
                        'sjdj': sjdj,
                        'hsj': hsj,
                        'bhse': Math.round(multiply(sjdj/1.17, sl) * 100) / 100,
                        // 'hse':Math.round(multiply(hsj, sl) * 100) / 100,
                        'hse': Math.round(multiply(sjdj, sl) * 100) / 100,
                        'je': Math.round(multiply(sjdj/1.17, sl) * 100) / 100,
                        // 'se':Math.round(multiply(hsj, sl) * 100) / 100 - Math.round(multiply(bhsj, sl) * 100) / 100,
                        'se': Math.round(multiply(sjdj, sl) * 100) / 100 - Math.round(multiply(sjdj/1.17, sl) * 100) / 100,
                        'ce': 0.0
                    });
                }
            })
            for (var i = 0; i < map.size(); i++) {
                cgjsdDsyfje += map.element(i).value;
            }
            $("#cgjsd_ddfy").val(formatJeForHtml2(cgjsdDsyfje));
            fillIntoFooter(); //统计净额、税额、面额、差额
        })
    });


}

//计算计划总量
/*function countSumCg() {
 var sumje = 0;
 var data = $("#grid_zjbcd").edatagrid("getData");
 for (var i = 0; i < data.rows.length; i++) {
 var je = parseFloat(data.rows[i]['je']);
 je = isNaN(je) ? 0 : je;
 sumje += je;
 }
 addFooter(sumje);
 }*/

/*function addFooter(sumje) {
 var footer = null;
 footer = [
 {"lb.id":"合计", "je":Math.round(sumje * 100) / 100}
 ];
 if (footer != null)
 $("#grid_zjbcd").edatagrid('reloadFooter', footer);
 }*/

/**
 *   统计grid_cgjsdmx的datagrid属性的数字累加
 * @param property
 * @return {Number}
 */
function initSumFooterCounts(property) {
    var cgdmxData = $("#grid_cgjsdmx").datagrid("getData");
    var sum = 0;
    $.each(cgdmxData.rows, function (i, val) {
        sum += parseFloat(val[property]);
    })
    return sum;
}
/**
 * 面额的统计
 * @return {Number}
 * @constructor
 */
function MeSumFooterCounts() {
    var cgdmxData = $("#grid_cgjsdmx").datagrid("getData");
    var sum = 0;
    $.each(cgdmxData.rows, function (i, val) {
        sum += (parseFloat(val['hsj']) * parseFloat(val['rksl']));
    })
    return sum;
}

//统计净额、税额、面额、差额
function fillIntoFooter() {
    var JeSum = initSumFooterCounts('je');
    var SeSum = initSumFooterCounts('se');
    var MeSum = JeSum + SeSum;//MeSumFooterCounts();
    var CeSum = initSumFooterCounts('ce');
    $('#cgjsd_me').val(formatJeForHtml2(MeSum));
    $('#cgjsd_je').val(formatJeForHtml2(JeSum));
    $('#cgjsd_se').val(formatJeForHtml2(SeSum));
    $('#cgjsd_ce').val(formatJeForHtml2(CeSum));

    fpzeSum(MeSum);

}

function fpzeSum(me) {
//    var ddyf = 0;
//    if ($('#cgjsd_ddfy').val()) {
//        ddyf = parseFloat($('#cgjsd_ddfy').val());
//    }
//    var me = $('#cgjsd_me').val();
//    me = me.replaceAll(',', '');
//    me = parseFloat(me);
//    $('#cgjsd_fpze').val(formatJeForHtml2(me + ddyf));
    $('#cgjsd_fpze').val(formatJeForHtml2(me));
}

function countMe() {
    var je = $('#cgjsd_je').val();
    je = je.replaceAll(',', '');
    je = parseFloat(je);
    var se = $('#cgjsd_se').val();
    se = se.replaceAll(',', '');
    se = parseFloat(se);
    return se + je;
}